<?php

namespace app\integration\kline;

use app\exception\CommonException;
use app\plugins\httpclient\HttpClient;
use think\facade\Cache;

class HuobiApi extends KlineApi
{

    public static $history_url = "/market/history/kline?period=[period]&size=300&symbol=[symbol]";
    const SERVICE = "huobi";

    public function getHistory(string $symbol, int $index)
    {
        $ttl = 0;
        $interval = "1min";
        switch ($index) {
            case self::TIME_SHARING:
                $ttl = 60;
                $interval = "1min";
                break;
            case self::TIME_DAY:
                $ttl = 3600 * 24 * 60;
                $interval = "1day";
                break;
            case self::TIME_WEEK:
                $ttl = 3600 * 24 * 60 * 7;
                $interval = "1week";
                break;
            case self::TIME_MONTH:
                $ttl = 3600 * 24 * 60 * 30;
                $interval = "1month";
                break;
            case self::TIME_YEAR:
                $ttl = 3600 * 24 * 60 * 30 * 12;
                $interval = "1year";
                break;
            case self::TIME_1MIN:
                $ttl = 60;
                $interval = "1min";
                break;
            case self::TIME_5MIN:
                $ttl = 5 * 60;
                $interval = "5min";
                break;
            case self::TIME_15MIN:
                $ttl = 15 * 60;
                $interval = "15min";
                break;
            case self::TIME_30MIN:
                $ttl = 30 * 60;
                $interval = "15min";
                break;
            case self::TIME_60MIN:
                $ttl = 60 * 60;
                $interval = "60min";
                break;
        }
        $key = "market.{$symbol}.kline.{$interval}";
        $data = Cache::store('redis')->get($key);
        if (!empty($data)) {
            return $data;
        }
        $httpClient = HttpClient::getInstance();
        $httpClient->init(self::SERVICE);
        $url = str_replace(["[period]", "[symbol]"], [$interval, $symbol], self::$history_url);
        $data = $httpClient->request($url, "get");
        if ($data["status"] != "ok") {
            throw new CommonException("获取数据错误");
        }
        Cache::store('redis')->set($key, $data, $ttl);
        return $data;

    }


    public function polling($symbol)
    {
        //$data =  Cache::store('redis')->get($symbol);;
        $str = "{\"id\":1760933040,\"open\":106781.68,\"close\":106790.07,\"low\":106778,\"high\":106790.07,\"amount\":0.004858999681131433,\"vol\":518.8664658099999,\"count\":7}";
        $data = json_decode($str, true);
        $close = $data["close"] + (rand(1, 100) / 100);
        $open = $data["open"] + (rand(1, 100) / 100);
        $data["open"] = round($open, 3);
        $data["close"] = round($close, 3);
        return ["data" => $data];
    }
}